#include "serialportbase.h"

namespace robot {

serial_error open_serialport(const char * port_name, open_mode mode,
		hdevice &hDev) {
#ifdef WIN32_VC_H
	hDev = CreateFile(port_name, mode, 0, NULL, OPEN_EXISTING, 0, NULL);
	if (reinterpret_cast<hdevice>(-1) == hDev) {
		return open_serialport_error;
	}
	return operator_success;
#endif

#ifdef LINUX_GCC_H
	hDev = open(port_name,mode);
	if (-1 == hDev) {
		return open_serialport_error;
	}
	return operator_success;
#endif
}

serial_error close_serialport(hdevice Dev) {
#ifdef WIN32_VC_H
	BOOL result = CloseHandle(Dev);
	if (!result) {
		return close_serialport_error;
	}
	return operator_success;
#endif

#ifdef LINUX_GCC_H
	close(Dev);
	return operator_success;
#endif
}

serial_error write_serialport(hdevice hDev, const char * buf, int size) {
#ifdef WIN32_VC_H
	DWORD length_of_buffer = size;
	BOOL result = WriteFile(hDev, buf, length_of_buffer, &length_of_buffer,
			NULL);
	if (!result) {
		return write_serialport_error;
	}
	return operator_success;
#endif

#ifdef LINUX_GCC_H
	int nByte = write(hDev,buf,size);
	if (nByte != size) {
		return read_serialport_error;
	}
	return operator_success;
#endif
}

serial_error read_serialport(hdevice hDev, char * buf, int size) {
#ifdef WIN32_VC_H
	DWORD length_of_buffer = size;
	BOOL result = ReadFile(hDev, buf, length_of_buffer, &length_of_buffer,
			NULL);
	if (!result) {
		return read_serialport_error;
	}
	return operator_success;
#endif

#ifdef LINUX_GCC_H
	int readByte = read(hDev,buf,size);
	return operator_success;
#endif
}

}
